package com.otr.ai.service;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.stereotype.Service;

@Service
public class McpClientService {
  private final ChatClient chatClient;

  /**
   *
   * @param toolCallbackProvider 会根据配置文件（SSE/STDIO）模式连接到MCP服务端，会结合上下文，如需会调用@Tool配置的方法
   */
  public McpClientService(
      ChatClient.Builder builder,
      ChatMemory chatMemory,
      ToolCallbackProvider toolCallbackProvider) {

    // 管理对话历史，确保多轮对话的连贯
    PromptChatMemoryAdvisor promptChatMemoryAdvisor = new PromptChatMemoryAdvisor(chatMemory);

    // 简单日志记录。
    SimpleLoggerAdvisor simpleLoggerAdvisor = new SimpleLoggerAdvisor();

    // 系统提示词
    String tips =
        """
        你是一名AI客服，你的任务是和蔼地回答用户的问题，处理客户要求的各种业务。
        """;
    this.chatClient =
        builder
            .defaultSystem(tips)
            .defaultAdvisors(simpleLoggerAdvisor,promptChatMemoryAdvisor)
            .defaultTools(toolCallbackProvider)
            .build();
  }

  public String chat(String chatId, String message) {
    return this.chatClient
        .prompt()
        .user(message)
        .advisors(advisorSpec -> advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
        .call()
        .content();
  }
}
